package com.example.mydy.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import androidx.security.crypto.EncryptedSharedPreferences;
import androidx.security.crypto.MasterKey;
import com.example.mydy.model.UserInfo;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 用户管理类，处理用户登录、注册、状态维护等
 */
public class UserManager {
    private static final String TAG = "UserManager";
    private static final String KEY_USER_INFO = "user_info";
    private static final String KEY_TOKEN = "user_token";
    private static final String ENCRYPTED_PREFS_FILE = "encrypted_user_prefs";
    private static UserManager instance;
    private UserInfo currentUser;
    private String token;
    private Context context;
    private SharedPreferences encryptedPrefs;

    private UserManager() {
        // 初始化代码（如有需要可在此添加）
    }

    public static UserManager getInstance() {
        if (instance == null) {
            synchronized (UserManager.class) {
                if (instance == null) {
                    instance = new UserManager();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化用户管理器
     * @param context 上下文
     */
    public void init(Context context) {
        this.context = context.getApplicationContext();
        try {
            MasterKey masterKey = new MasterKey.Builder(context)
                .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
                .build();

            encryptedPrefs = EncryptedSharedPreferences.create(
                context,
                ENCRYPTED_PREFS_FILE,
                masterKey,
                EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
            );
            
            loadUserInfoFromLocal();
        } catch (Exception e) {
            Log.e(TAG, "初始化加密SharedPreferences失败", e);
        }
    }

    /**
     * 从本地存储加载用户信息
     */
    private void loadUserInfoFromLocal() {
        if (encryptedPrefs != null) {
            String userJson = encryptedPrefs.getString(KEY_USER_INFO, "");
            String savedToken = encryptedPrefs.getString(KEY_TOKEN, "");
            
            if (!TextUtils.isEmpty(userJson)) {
                try {
                    currentUser = new Gson().fromJson(userJson, UserInfo.class);
                    Log.d(TAG, "成功从本地加载用户信息");
                } catch (Exception e) {
                    Log.e(TAG, "解析本地用户信息失败: " + e.getMessage());
                }
            }
            
            if (!TextUtils.isEmpty(savedToken)) {
                token = savedToken;
                Log.d(TAG, "成功从本地加载用户令牌");
            }
        }
    }

    /**
     * 保存用户信息到本地
     */
    private void saveUserInfoToLocal() {
        if (encryptedPrefs != null) {
            SharedPreferences.Editor editor = encryptedPrefs.edit();
            
            if (currentUser != null) {
                String userJson = new Gson().toJson(currentUser);
                editor.putString(KEY_USER_INFO, userJson);
            }
            
            if (token != null) {
                editor.putString(KEY_TOKEN, token);
            }
            
            editor.apply();
        }
    }

    /**
     * 获取当前用户
     * @return 当前登录的用户，未登录则返回null
     */
    public UserInfo getCurrentUser() {
        return currentUser;
    }

    /**
     * 获取认证令牌
     * @return 认证令牌
     */
    public String getToken() {
        return token;
    }

    /**
     * 判断用户是否已登录
     * @return 是否已登录
     */
    public boolean isLoggedIn() {
        return currentUser != null && !TextUtils.isEmpty(token);
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @param callback 登录结果回调
     */
    public void login(String username, String password, final LoginCallback callback) {
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            if (callback != null) {
                callback.onFailed("用户名和密码不能为空");
            }
            return;
        }

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("username", username);
            jsonObject.put("password", password);

            NetworkUtils.post("/user/login", jsonObject.toString(), new Callback<ResponseBody>() {
                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    if (callback != null) {
                        callback.onFailed("网络请求失败: " + t.getMessage());
                    }
                }

                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        if (response.isSuccessful() && response.body() != null) {
                            String responseString = response.body().string();
                            JSONObject jsonResponse = new JSONObject(responseString);
                            String token = jsonResponse.getString("token");
                            NetworkUtils.saveAuthToken(context, token);
                            loadUserInfo();
                        } else {
                            if (callback != null) {
                                callback.onFailed("登录失败: " + response.code());
                            }
                        }
                    } catch (Exception e) {
                        if (callback != null) {
                            callback.onFailed("解析响应失败: " + e.getMessage());
                        }
                    }
                }
            });
        } catch (Exception e) {
            if (callback != null) {
                callback.onFailed("创建请求失败: " + e.getMessage());
            }
        }
    }

    /**
     * 注销当前用户
     */
    public void logout() {
        currentUser = null;
        token = null;
        if (encryptedPrefs != null) {
            encryptedPrefs.edit()
                .remove(KEY_USER_INFO)
                .remove(KEY_TOKEN)
                .apply();
        }
    }

    /**
     * 刷新用户信息
     * @param callback 刷新结果回调
     */
    public void refreshUserInfo(final RefreshCallback callback) {
        if (!isLoggedIn()) {
            if (callback != null) {
                callback.onFailed("用户未登录");
            }
            return;
        }

        NetworkUtils.get("/user/info", new Callback<ResponseBody>() {
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (callback != null) {
                    callback.onFailed("网络请求失败: " + t.getMessage());
                }
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.isSuccessful() && response.body() != null) {
                        String responseString = response.body().string();
                        JSONObject jsonResponse = new JSONObject(responseString);
                        UserInfo userInfo = new Gson().fromJson(jsonResponse.toString(), UserInfo.class);
                        currentUser = userInfo;
                        if (callback != null) {
                            callback.onSuccess(userInfo);
                        }
                    } else {
                        if (callback != null) {
                            callback.onFailed("获取用户信息失败: " + response.code());
                        }
                    }
                } catch (Exception e) {
                    if (callback != null) {
                        callback.onFailed("解析用户信息失败: " + e.getMessage());
                    }
                }
            }
        });
    }

    /**
     * 加载用户信息
     */
    public void loadUserInfo() {
        if (!isLoggedIn()) {
            Log.w(TAG, "尝试加载用户信息，但用户未登录");
            return;
        }
        
        refreshUserInfo(new RefreshCallback() {
            @Override
            public void onSuccess(UserInfo user) {
                Log.d(TAG, "用户信息刷新成功");
            }
            
            @Override
            public void onFailed(String message) {
                Log.e(TAG, "刷新用户信息失败: " + message);
            }
        });
    }

    /**
     * 登录回调接口
     */
    public interface LoginCallback {
        void onSuccess(UserInfo user);
        void onFailed(String message);
    }

    /**
     * 刷新用户信息回调接口
     */
    public interface RefreshCallback {
        void onSuccess(UserInfo user);
        void onFailed(String message);
    }
}